package com.szty.libarytest.other

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.room.Room
import com.szty.libarytest.R
import com.szty.libarytest.room.AppDatabase
import com.szty.libarytest.room.User
import kotlinx.android.synthetic.main.activity_room_test.*

class RoomTestActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_room_test)
        val db =
            Room.databaseBuilder(applicationContext, AppDatabase::class.java, "user1-name")
                .fallbackToDestructiveMigration()               //在数据库升级失败的情况下，重新创建数据库，但是会丢失之前的数据
                .allowMainThreadQueries()                       //强制可以在主线程运行
                .build()
        btn_getdata_sql.setOnClickListener {
            db.userDao().getAll().forEach {
                it.uid.loge("uid")
                it.firstName.loge("name")
            }
        }
        btn_save_data.setOnClickListener {
            val name = ed_input_name.text.toString()
            val number = ed_input_number.text.toString().toIntOrNull()?:0
            db.userDao().insertAll(User(firstName =name, number = number))
        }
        btn_delete_data.setOnClickListener {
            val lastData = db.userDao().getFirstData() ?: return@setOnClickListener
            db.userDao().delete(lastData)
            lastData.uid.loge("被删除")
            val user = db.userDao().getFirstData() ?: return@setOnClickListener
            user.uid.loge("删除测试")
        }
        btn_clear_data.setOnClickListener {
        }
    }
}